import redis
import time
import hmac
import base64
import hashlib
from urllib.parse import quote
from common.config_parse import parse_ini
from common.operate_db import MySql
from common.log import Log

ddconfig = parse_ini('dingding') #取钉钉的配置信息
secret = ddconfig.get("secret")

redis_conn_mapper ={}
mysql_conn_mapper={}
def get_mysql_old(node='mysql',db=None):

    key = '%s%s'%(node,db)
    if not key in mysql_conn_mapper:

        mysql_info = parse_ini(node)
        if db:
            mysql_info['db']=db
        mysql = MySql(**mysql_info)
        mysql_conn_mapper[key] = mysql
    else:
        mysql = mysql_conn_mapper[key]

    return mysql

def get_mysql(node='mysql',db=None,cursor_type = 'dict'):

        mysql_info = parse_ini(node)
        if db:
            mysql_info['db']=db
        mysql = MySql(**mysql_info,cursor_type = cursor_type)

        return mysql

def get_redis(node='redis',db=None):

    key = '%s%s'%(node,db)

    if not key in redis_conn_mapper:

        redis_info = parse_ini(node)
        if db:
            redis_info['db']=db
        r = redis.Redis(**redis_info,decode_responses=True)#decode_responses=True,默认返回字符串
        Log.info('开始连接redis')
        redis_conn_mapper[key] = r
    else:
        r = redis_conn_mapper[key]

    return r

def create_sign():
    timestamp = int(time.time() * 1000)
    sign_before  = '%s\n%s' % (timestamp,secret)
    hsha265 = hmac.new(secret.encode(),sign_before.encode(),hashlib.sha256)
    sign_sha256 = hsha265.digest()
    sign_b64 = base64.b64encode(sign_sha256)
    sign = quote(sign_b64)
    return {"timestamp":timestamp,"sign":sign}

if __name__ == '__main__':
    get_redis('redis')
